Page({
  data: {
    activeKey: 0,
    goodList: [], // 初始为空数组，从数据库获取
    allGoods: [], // 存储从数据库获取的所有数据
    tab: ['全部','外套','内搭','下装','一体衣','鞋子','装饰','袜子','帽子'],
    TabIndex: '0',
    currentImage: '/images/all.png',
    tabImages: {
      '全部': '/images/all.png',
      '外套': '/images/all.png',
      '内搭': '/images/all.png',
      '下装': '/images/pants.png',
      '一体衣': '/images/dress.png',
      '鞋子': '/images/shoes.png',
      '装饰': '/images/accessory.png',
      '袜子': '/images/socks.png',
      '帽子': '/images/hat.png'
    },
    selectedItem: null, // 当前选中的衣物索引
    selectType: '' // 从attire页面传递过来的衣物类型
  },
  
  clickTab(e) {
    const index = e.currentTarget.dataset.id;
    const tabName = this.data.tab[index];
    
    this.setData({
      TabIndex: index,
      currentImage: this.data.tabImages[tabName]
    });
    
    const category = this.data.tab[index];
    let filteredList = [];
    
    // 修改比较逻辑，确保类型一致
    if (index == 0) { // 全部
      filteredList = [...this.data.allGoods];
    } else {
      filteredList = this.data.allGoods.filter(item => 
        item.categories === category
      );
    }
    
    this.setData({
      TabIndex: index,
      goodList: filteredList
    });
  },
  
  
  // 添加选择衣物方法
  onLoad: function(options) {
    const selectedType = wx.getStorageSync('selectedClosetType');
    console.log('[onLoad] 从attire传递的选择类型:', selectedType);
    
    this.setData({
      selectType: selectedType,
      isFromAttire: !!selectedType
    });
  },
  
  onShow: function() {
    // 重置选中状态但保留selectType
    this.setData({
      selectedItem: null
    });
    
    // 用户登录检查
    let userinfo = wx.getStorageSync('userinfo');
    if (!userinfo) {
      return wx.reLaunch({ url: '/pages/login/login' });
    }
    
    this.loadClothesData();
  },
  
  onSelectItem: function(e) {
    console.log('[onSelectItem] 当前状态:', {
      isFromAttire: this.data.isFromAttire,
      selectType: this.data.selectType
    });
    
    if (!this.data.isFromAttire || !this.data.selectType) {
      console.log('选择失败：未正确设置selectType');
      return;
    }
  
    const index = e.currentTarget.dataset.index;
    const item = e.currentTarget.dataset.item;
    
    // 只存储item数据
    wx.setStorageSync('selectedClosetItem', {
      img: item.img || '',
      categories: item.categories || '',
      colors: item.colors || '',
      styles: item.styles || '',
      seasons: item.seasons || '',
      value: item.value || 0,
      time: item.time || new Date().toISOString().split('T')[0]
    });
  
    
    wx.switchTab({
      url: '/pages/attire/attire'
    });
  },
  // 从云数据库加载衣物数据
  async loadClothesData() {
    try {
      wx.showLoading({ title: '加载中...' });
      
      // 获取当前用户信息
      const userinfo = wx.getStorageSync('userinfo');
      if (!userinfo || !userinfo._id) {
        throw new Error('用户未登录');
      }
      console.log('加载数据的用户ID:', userinfo._id);
      
      // 调用云函数查询数据
      const res = await wx.cloud.callFunction({
        name: 'clothes',
        data: {
          action: 'query',
          query: {
            userid: userinfo._id,  // 直接使用userid作为查询条件
            orderBy: 'time',
            order: 'desc'
          }
        }
      });

      // 保存全部数据和当前显示数据
      this.setData({
        allGoods: res.result.data,
        goodList: res.result.data
      });
      
      wx.hideLoading();
    } catch (err) {
      console.error('加载失败:', err);
      wx.hideLoading();
      wx.showToast({ 
        title: '加载失败: ' + (err.errMsg || err.message), 
        icon: 'error' 
      });
    }
  }
});